package pixelradar.tasks;

import net.minecraft.util.math.ChunkPos;
import pixelradar.Mw;
import pixelradar.map.MapTexture;
import pixelradar.region.MwChunk;
import pixelradar.region.RegionManager;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class UpdateSurfaceChunksTask extends Task {
    private static final Map<Long, UpdateSurfaceChunksTask> chunksUpdating = new HashMap<>();
    private MwChunk chunk;
    private final RegionManager regionManager;
    private final MapTexture mapTexture;
    private final AtomicBoolean Running = new AtomicBoolean();

    public UpdateSurfaceChunksTask(Mw mw, MwChunk chunk) {
        this.mapTexture = mw.mapTexture;
        this.regionManager = mw.regionManager;
        this.chunk = chunk;
    }

    public void run() {
        this.Running.set(true);
        if (this.chunk != null) {
            this.regionManager.updateChunk(this.chunk);
            this.mapTexture.updateArea(this.regionManager, this.chunk.x << 4, this.chunk.z << 4, 16, 16, this.chunk.dimension);
        }

    }

    public void onComplete() {
        Long coords = this.chunk.getCoordIntPair();
        chunksUpdating.remove(coords);
        this.Running.set(false);
    }

    public void updateChunkData(MwChunk chunk) {
        this.chunk = chunk;
    }

    public boolean checkForDuplicate() {
        Long coords = ChunkPos.asLong(this.chunk.x, this.chunk.z);
        if (!chunksUpdating.containsKey(coords)) {
            chunksUpdating.put(coords, this);
            return false;
        } else {
            UpdateSurfaceChunksTask task2 = chunksUpdating.get(coords);
            if (!task2.Running.get()) {
                task2.updateChunkData(this.chunk);
                return true;
            } else {
                chunksUpdating.put(coords, this);
                return false;
            }
        }
    }
}
